﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Configuration;
using System.Data;
using System.Xml;


public partial class login : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }



    protected void Login1_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
    {
        FormsAuthentication.SignOut(); // izlogojās no default Login True Režīma

        string username;
        string pwd;
        string CurrentUser = "";
        string CurrentPwd = "";
        bool LoginStatus = false;

        username = Login1.UserName;
        pwd = Login1.Password;

        XmlDocument xd = new XmlDocument();
        xd.Load(Server.MapPath("~/App_Data/AllUser.xml"));

        XmlNodeList xnl = xd.GetElementsByTagName("User");

        foreach (XmlNode xn in xnl)
        {
            XmlNodeList cxnl = xn.ChildNodes;
            foreach (XmlNode cxn in cxnl)
            {
                if (cxn.Name == "username")
                {
                    if (cxn.InnerText == username)
                    {
                        CurrentUser = username;
                    }
                }

                if (cxn.Name == "password")
                {
                    if (cxn.InnerText == pwd)
                    {
                        CurrentPwd = pwd;
                    }
                }
            }

            if ((CurrentUser != "") & (CurrentPwd != ""))
            {
                LoginStatus = true;
            }
        }

        if (LoginStatus == true)
        {
            Session["UserAuthentication"] = username;
            Session.Timeout = 1;
            FormsAuthentication.SetAuthCookie("EpisLog", false);
            //modify the Domain attribute of the cookie to the second level of domain
            System.Web.HttpCookie MyCookie = System.Web.Security.FormsAuthentication.GetAuthCookie(User.Identity.Name.ToString(), false);
            MyCookie.Domain = ConfigurationManager.AppSettings["Level2DomainName"];//like miscrosoft.com, dell.com...
            Response.AppendCookie(MyCookie);

            Response.Redirect("~/login_izvele.aspx");

        }
        else
        {
            Session["UserAuthentication"] = "";
        }
    }
}
